<template>
  <div class="nodeviewbox">
    <div class="nodeview" style="position: absolute; z-index: -1;" >{{ text }}</div>
    <div class="nodeview" ref="nodeview" >{{ text }}</div>
  </div>
</template>

<script>
import { TweenMax } from 'gsap'
import Draggable from 'gsap/Draggable'

export default {
  props: {
    name: {
      default: ''
    },
    category: {
      default: 1
    }
  },
  data () {
    return {
      container: {}
    }
  },
  methods: {
    isEnterBox (event, rect) {
      return event.clientX > rect.left && event.clientX < rect.right && event.clientY > rect.top && event.clientY < rect.bottom
    },
    init (container) {
      this.container = container
      const dom = this.container.$el
      let offsetX
      let offsetY
      this.node = Draggable.create(this.$refs.nodeview, {
        type: 'x,y',
        edgeResistance: 0.65,
        cursor: 'default',
        activeCursor: 'default',
        inertia: true,
        onPress: event => {
          offsetX = event.offsetX
          offsetY = event.offsetY
          // console.log(event.offsetX, event.offsetY)
        },
        onDragEnd: event => {
          const rect = dom.getBoundingClientRect()
          if (!this.isEnterBox(event, rect)) {
            TweenMax.to(this.$refs.nodeview, 0.5, { x: 0, y: 0 })
          } else {
            TweenMax.to(this.$refs.nodeview, 0, { x: 0, y: 0 })
            const point = this.container.getPoint(event)
            // const x = event.clientX - offsetX - rect.left - 1
            // const y = event.clientY - offsetY - rect.top - 1
            const x = point.x - offsetX - 1
            const y = point.y - offsetY - 1
            container.addNode({ x, y, text: '新节点' }, true)
            // console.log(node)
            // node.init(container)
          }
        }
      })[0]
    }
  },
  computed: {
    text () {
      if (this.category === 1) {
        return '节点'
      }
      return ''
    }
  },
  mounted () {}
}
</script>

<style lang="scss">
  .nodeviewbox {
    width: 120px;
    margin: 10px auto;
    box-sizing: border-box;
  }
  .nodeview {
    border-radius: 5px;
    width: 120px;
    height: 30px;
    background-color: #409eff;
    border: 1px solid #666;
    line-height: 30px;
  }
</style>
